package com.wawayaya.bookreader;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

/**
 * Created by wang_qian on 2015/6/25.
 */
public class TouchMoveLinearLayout extends LinearLayout {
    private Context mContext;
    private int      mScreenWidth;
    private int      mScreenHeight;
   // private int      mMargin;

    public TouchMoveLinearLayout(Context context) {
        super(context);
        mContext = context;

    }

    public TouchMoveLinearLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;

    }

    public TouchMoveLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;

    }

    public void setScreenSize(int width , int height) {
        mScreenWidth = width;
        mScreenHeight = height;
        //mMargin = (int)mContext.getResources().getDimension(R.dimen.trans_layout_move_magin);
    }

    int  last_x = 0;
    int  last_y = 0;

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        int x = (int)event.getRawX();
        int y = (int)event.getRawY();
        switch(event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                last_x = x;
                last_y = y;

                break;
            case MotionEvent.ACTION_MOVE:
                changePosition(x - last_x, y - last_y);
                last_x = x;
                last_y = y;
                break;
            case MotionEvent.ACTION_UP:
                changePosition(x - last_x , y - last_y);
                break;
            case MotionEvent.ACTION_CANCEL:
                break;
            case MotionEvent.ACTION_OUTSIDE:
                break;
        }
        return true;
    }


    private boolean changePosition(int x_offset, int y_offset) {
        RelativeLayout.LayoutParams rp = (RelativeLayout.LayoutParams)getLayoutParams();
        int width = getWidth();
        int height = getHeight();
        if (rp != null) {
           int new_left_margin = rp.leftMargin + x_offset;
           if (new_left_margin < 0 || (new_left_margin + width) > mScreenWidth) {
               return false;
           }
           int new_top_margin = rp.topMargin + y_offset;
           if (new_top_margin < 0 || (new_top_margin + height) > mScreenHeight) {
               return false;
           }
           rp.leftMargin =  new_left_margin;
           rp.topMargin = new_top_margin;
           setLayoutParams(rp);
           return true;
        }
        return false;
    }
}
